package com.itboye.eweilisten.me.login;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.itboye.eweilisten.R;
import com.itboye.eweilisten.base.BaseActivity;
import com.itboye.eweilisten.main.MainActivity;
import com.itboye.eweilisten.model.DiaoChaBean;
import com.itboye.eweilisten.presenter.UserPresenter;
import com.itboye.eweilisten.util.loadingutil.MAlert;
import com.itboye.eweilisten.util.widget.IsStringSPUtils;
import com.itboye.eweilisten.util.widget.MyListView;
import com.itboye.eweilisten.volley.ResultEntity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

/**
 * Created by itboye on 2017/3/14.
 */

public class ActivityDiaoCha extends BaseActivity implements Observer {
    private MyListView lsitviewdiaocha;
    private MyAdapter myAdapter;
    private Button button;
    List<DiaoChaBean> myList;
    DiaoChaBean bean;
    UserPresenter presenter;
    List<String> ids = new ArrayList<String>();
    private TextView tvdiaocha;
    private TextView tvTitle;
    /*json*/
    private JSONObject object; // JSONObject对象，处理一个一个的对象
    private JSONObject objPatientInfo;
    private JSONArray jsonArrayPatientInfo;// JSONObject对象，处理一个一个集合或者数组
    private String jsonString; // 保存带集合的json字符串
    private ImageView back;

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);

        setContentView(R.layout.activity_diaocha);
        init();
        button.setVisibility(View.GONE);
        bean=new DiaoChaBean();
        presenter = new UserPresenter(this);
        presenter.onDiaocha(IsStringSPUtils.IsUid(),IsStringSPUtils.getSid());
        showProgressDialog("数据加载中...", true);

    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.back:
                this.finish();
                break;
        }
    }

    // 把一个集合转换成json格式的字符串
    private void changeArrayDateToJson() {
        String str = null;
        ids.clear();
        if (myAdapter.flage) {
            for (int i = 0; i < myList.size(); i++) {
                for (int j = 0; j < myList.get(i).getChild().size(); j++) {
                    if (myList.get(i).getChild().get(j).isCheck) {
                        ids.add(myList.get(i).getChild().get(j).getId());
                        myList.get(i).getChild().get(j).setId(ids.toString().substring(1,
                                ids.toString().length() - 1));
                        str = myList.get(i).getChild().get(j).getId();
                        System.out.println("modelmodelmodelisd"
                                + ids.size());
                    }
                }

            }
            if (ids.toString().length() > 2) {
                for (int i = 0; i < myList.size(); i++) {
                    for (int j = 0; j < myList.get(i).getChild().size(); j++) {
                        myList.get(i).getChild().get(j).setId(ids.toString().substring(1,
                                ids.toString().length() - 1));
                    }
                }

            } else {
//                toast(getString(R.string.h1188));
                MAlert.alert("您还没没有选择");
            }
        }

        if (str == null) {
            MAlert.alert("您还未选中");
        } else {
            jsonArrayPatientInfo = null;
            object = null;
            jsonArrayPatientInfo = new JSONArray();
            object = new JSONObject();
            // 遍历上面初始化的集合数据，把数据加入JSONObject里面
            for (int i = 0; i < myList.size(); i++) {
                // 一个user对象，使用一个JSONObject对象来装
                objPatientInfo = new JSONObject();
                try {
                    // 从集合取出数据，放入JSONObject里面 JSONObject对象和map差不多用法,以键和值形式存储数据
                    for (int j = 0; j < myList.get(i).getChild().size(); j++) {
                        objPatientInfo.put(myList.get(i).getId(), myList.get(i)
                                .getChild().get(j).getId());
                    }
                    // 把JSONObject对象装入jsonArray数组里面
                    jsonArrayPatientInfo.put(str);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            try {
                // 再把JSONArray数据加入JSONObject对象里面(数组也是对象)
                for (int i = 0; i < myList.size(); i++) {
                    object.put(myList.get(i).getId(), jsonArrayPatientInfo);
                }


                // object.put("time", "2013-11-14");
                // //这里还可以加入数据，这样json型字符串，就既有集合，又有普通数据
            } catch (JSONException e) {
                e.printStackTrace();
            }
            jsonString = null;
            // 把JSONObject转换成json格式的字符串
            jsonString = object.toString();
//        textView.setText(jsonString);
            presenter.onTiJiaoWenJuan(jsonString,IsStringSPUtils.IsUid(),IsStringSPUtils.getSid());
            showProgressDialog("提交中...", true);
            Log.i("输出json字符串", "转换成json字符串: " + jsonString);
        }
    }

    public void init() {
        tvTitle.setText("调查表");
        myList = new ArrayList<>();

        lsitviewdiaocha.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                myList.get(0).getChild().get(position).isCheck=!myList.get(0).getChild().get(position).isCheck;
                myAdapter.notifyDataSetChanged();
            }
        });
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeArrayDateToJson();


            }
        });
    }

    @Override
    public void update(Observable o, Object arg) {
        ResultEntity entity = handlerError(arg);
        if (entity != null) {
            if (entity.getEventType() == presenter.Diaocha_success) {
                myList = (List<DiaoChaBean>) entity.getData();
                button.setVisibility(View.VISIBLE);
                tvdiaocha.setText(myList.get(0).getName());

                myAdapter = new MyAdapter(ActivityDiaoCha.this, myList);
                lsitviewdiaocha.setAdapter(myAdapter);


                closeProgressDialog();
            } else if (entity.getEventType() == presenter.Tijiao_success) {
                MAlert.alert("提交成功!");
                closeProgressDialog();
                Intent intent = new Intent(ActivityDiaoCha.this, MainActivity.class);
                startActivity(intent);
                finish();
            }else if(entity.getEventType() == presenter.Tijiao_fail){
                MAlert.alert(entity.getData()+"");
            }
        }
    }


    //自定义adapter
    private static class MyAdapter extends BaseAdapter {
        public boolean flage = true;
        public Map<Integer, String> selected;
        private LayoutInflater inflater;
        List<DiaoChaBean> myList;


        public MyAdapter(Context context, List<DiaoChaBean> myList) {
            this.inflater = LayoutInflater.from(context);
            this.myList = myList;
            selected = new HashMap<Integer, String>();

        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return myList.get(0).getChild().size();
        }

        @Override
        public Object getItem(int arg0) {
            // TODO Auto-generated method stub
            return arg0;
        }

        @Override
        public long getItemId(int arg0) {
            // TODO Auto-generated method stub
            return arg0;
        }

        @Override
        public View getView(final int position, View convertView,
                            ViewGroup parent) {
            Log.i("aaa", "getview");
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.layout_item, null);
                holder = new ViewHolder();
                holder.txt = (TextView) convertView.findViewById(R.id.txt);
                holder.checkBox = (CheckBox) convertView
                        .findViewById(R.id.checkBox);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            Log.d("checkbox",myList.get(0).getChild().get(position).isCheck+"");
            holder.checkBox.setChecked(myList.get(0).getChild().get(position).isCheck);
            for (int i = 0; i < myList.size(); i++) {
                holder.txt.setText(myList.get(i).getChild().get(position).getName());
            }
            holder.checkBox.setTag(position);

            holder.checkBox.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    CheckBox cb = (CheckBox)v;
                    myList.get(0).getChild().get(position).isCheck = cb.isChecked();

                }
            });
            return convertView;
        }


        public class ViewHolder {
            public TextView txt;
            public CheckBox checkBox;

        }
    }
}
